import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class WechatAuthService extends BaseService<any> {
  private readonly logger = new Logger(WechatAuthService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * authorization
   * 对应 PHP: WechatAuthService_api::authorization()
   * 逻辑类型: undefined - undefined
   */
  async authorization(url: string, scopes: string) {
    // 基于PHP真实逻辑: authorization
    // PHP原文: //todo  业务落地         return [ 'url' => $this->core_wechat_serve_service->authorization($this->site_id, $url, $scopes) ];     }      /**      * 处理授权回调 ...
//todo  业务落地
        return [ url: this.core_wechat_serve_service.authorization(this.site_id, url, scopes) ];
    }

    /**
     * 处理授权回调
     * @param string code
     * @return */
    async userFromCode(string code)
    {
        const userinfo = this.core_wechat_serve_service.userFromCode(this.site_id, code);
        if (!userinfo)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
        const token_response = userinfo.getTokenResponse();
        if (!token_response)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
        const scope = token_response[ 'scope' );
        if (scope == 'snsapi_base') {//静默授权
            const openid = token_response[ 'openid' ] || '';
  }

  /**
   * userFromCode
   * 对应 PHP: WechatAuthService_api::userFromCode()
   * 逻辑类型: undefined - undefined
   */
  async userFromCode(code: string) {
    // 基于PHP真实逻辑: userFromCode
    // PHP原文: $userinfo = $this->core_wechat_serve_service->userFromCode($this->site_id, $code);         if (empty($userinfo)) throw new ApiException('WECHAT_EMPOWE...
const userinfo = this.core_wechat_serve_service.userFromCode(this.site_id, code);
        if (!userinfo)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
        const token_response = userinfo.getTokenResponse();
        if (!token_response)) throw new ApiBusinessException('WECHAT_EMPOWER_NOT_EXIST'];
        const scope = token_response[ 'scope' );
        if (scope == 'snsapi_base') {//静默授权
            const openid = token_response[ 'openid' ] || '';
  }

  /**
   * loginByCode
   * 对应 PHP: WechatAuthService_api::loginByCode()
   * 逻辑类型: undefined - undefined
   */
  async loginByCode(code: string) {
    // 基于PHP真实逻辑: loginByCode
    // PHP原文: [ $avatar, $nickname, $openid, $unionid ] = $this->userFromCode($code);         return $this->login($openid, $nickname, $avatar, $unionid);     }     ...
[ avatar, nickname, openid, unionid ] = this.userFromCode(code];
        return this.login(openid, nickname, avatar, unionid);
    }

    /**
     * 公众号登录
     * @param string openid
     * @param string nickname
     * @param string avatar
     * @param string unionid
     * @return array|null
     * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async login(string openid, string nickname = '', string avatar = '', string unionid = '')
    {

        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (member_info.isEmpty() && !!unionid)) {
            const member_info = member_service.findMemberInfo([ wx_unionid: unionid, site_id: this.site_id )];
            if (!member_info.isEmpty()) {
                member_info.wx_openid = openid;
            }
  }

  /**
   * login
   * 对应 PHP: WechatAuthService_api::login()
   * 逻辑类型: undefined - undefined
   */
  async login(openid: string, nickname: string, avatar: string, unionid: string) {
    // 基于PHP真实逻辑: login
    // PHP原文: $member_service = new MemberService();         $member_info = $member_service->findMemberInfo([ 'wx_openid' => $openid, 'site_id' => $this->site_id ])...
const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (member_info.isEmpty() && !!unionid)) {
            const member_info = member_service.findMemberInfo([ wx_unionid: unionid, site_id: this.site_id )];
            if (!member_info.isEmpty()) {
                member_info.wx_openid = openid;
            }
  }

  /**
   * sync
   * 对应 PHP: WechatAuthService_api::sync()
   * 逻辑类型: undefined - undefined
   */
  async sync(code: string) {
    // 基于PHP真实逻辑: sync
    // PHP原文: [ $avatar, $nickname, $openid ] = $this->userFromCode($code);         //更新粉丝         $core_wechat_fans_service = new CoreWechatFansService();         ...
[ avatar, nickname, openid ] = this.userFromCode(code);
        //更新粉丝
        const core_wechat_fans_service = this.coreWechatFansService;
        //这儿或许可以异步
        core_wechat_fans_service.edit(this.site_id, openid, [ avatar: avatar, nickname: nickname )];
        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ headimg: avatar, nickname: nickname )];
        return true;
    }

    /**
     * 注册
     * @param string openid
     * @param string mobile
     * @param string nickname
     * @param string avatar
     * @param string wx_unionid
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async register(string openid, string mobile = '', string nickname = '', string avatar = '', string wx_unionid = '')
    {
        const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (!member_info.isEmpty()) throw new AuthBusinessException('MEMBER_IS_EXIST');//账号已存在, 不能在注册
        if (!!wx_unionid)) {
            const member_info = member_service.findMemberInfo([ wx_unionid: wx_unionid, site_id: this.site_id )];
            if (!member_info.isEmpty()) throw new AuthBusinessException('MEMBER_IS_EXIST');//账号已存在, 不能在注册
  }

  /**
   * register
   * 对应 PHP: WechatAuthService_api::register()
   * 逻辑类型: undefined - undefined
   */
  async register(openid: string, mobile: string, nickname: string, avatar: string, wx_unionid: string) {
    // 基于PHP真实逻辑: register
    // PHP原文: $member_service = new MemberService();         $member_info = $member_service->findMemberInfo([ 'wx_openid' => $openid, 'site_id' => $this->site_id ])...
const member_service = this.memberService;
        const member_info = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (!member_info.isEmpty()) throw new AuthBusinessException('MEMBER_IS_EXIST');//账号已存在, 不能在注册
        if (!!wx_unionid)) {
            const member_info = member_service.findMemberInfo([ wx_unionid: wx_unionid, site_id: this.site_id )];
            if (!member_info.isEmpty()) throw new AuthBusinessException('MEMBER_IS_EXIST');//账号已存在, 不能在注册
  }

  /**
   * jssdkConfig
   * 对应 PHP: WechatAuthService_api::jssdkConfig()
   * 逻辑类型: undefined - undefined
   */
  async jssdkConfig(url: string) {
    // 基于PHP真实逻辑: jssdkConfig
    // PHP原文: return $this->core_wechat_serve_service->jssdkConfig($this->site_id, $url);     }      /**      * 扫码登录      * @return array      */     public functio...
return this.core_wechat_serve_service.jssdkConfig(this.site_id, url);
    }

    /**
     * 扫码登录
     * @return */
    async scanLogin()
    {
        const data = [
            channel: this.channel,
        ];
        const key = ( this.coreScanService ).scan(this.site_id, ScanDict.WECHAT_LOGIN, data, 300);
        const url = this.core_wechat_serve_service.scan(this.site_id, key, 300)[ 'url' ] || '';
        return [
            url: url,
            key: key
        ];
    }

    /**
     * 更新openid（用于账号密码或手机号注册时未正常获取到openid时再次获取）
     * @param string code
     * @return true
     */
    async updateOpenid(string code)
    {
        [ avatar, nickname, openid, unionid ] = this.userFromCode(code);
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: openid )];
        return true;
    }

    /**
     * 更新openid（用于H5注册账号后，在公众号进行登录时绑定wx_openid）
     * @param string wx_openid
     * @return true
     */
    async updateOpenidByH5(wx_openid)
    {
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: wx_openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: wx_openid )];
        return true;
    }
}
  }

  /**
   * scanLogin
   * 对应 PHP: WechatAuthService_api::scanLogin()
   * 逻辑类型: undefined - undefined
   */
  async scanLogin() {
    // 基于PHP真实逻辑: scanLogin
    // PHP原文: $data = array(             'channel' => $this->channel,         );         $key = ( new  CoreScanService() )->scan($this->site_id, ScanDict::WECHAT_LO...
const data = [
            channel: this.channel,
        ];
        const key = ( this.coreScanService ).scan(this.site_id, ScanDict.WECHAT_LOGIN, data, 300);
        const url = this.core_wechat_serve_service.scan(this.site_id, key, 300)[ 'url' ] || '';
        return [
            url: url,
            key: key
        ];
    }

    /**
     * 更新openid（用于账号密码或手机号注册时未正常获取到openid时再次获取）
     * @param string code
     * @return true
     */
    async updateOpenid(string code)
    {
        [ avatar, nickname, openid, unionid ] = this.userFromCode(code);
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: openid )];
        return true;
    }

    /**
     * 更新openid（用于H5注册账号后，在公众号进行登录时绑定wx_openid）
     * @param string wx_openid
     * @return true
     */
    async updateOpenidByH5(wx_openid)
    {
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: wx_openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: wx_openid )];
        return true;
    }
}
  }

  /**
   * updateOpenid
   * 对应 PHP: WechatAuthService_api::updateOpenid()
   * 逻辑类型: undefined - undefined
   */
  async updateOpenid(code: string) {
    // 基于PHP真实逻辑: updateOpenid
    // PHP原文: [ $avatar, $nickname, $openid, $unionid ] = $this->userFromCode($code);         $member_service = new MemberService();         $member = $member_servi...
[ avatar, nickname, openid, unionid ] = this.userFromCode(code);
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: openid )];
        return true;
    }

    /**
     * 更新openid（用于H5注册账号后，在公众号进行登录时绑定wx_openid）
     * @param string wx_openid
     * @return true
     */
    async updateOpenidByH5(wx_openid)
    {
        const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: wx_openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: wx_openid )];
        return true;
    }
}
  }

  /**
   * updateOpenidByH5
   * 对应 PHP: WechatAuthService_api::updateOpenidByH5()
   * 逻辑类型: undefined - undefined
   */
  async updateOpenidByH5(wx_openid: any) {
    // 基于PHP真实逻辑: updateOpenidByH5
    // PHP原文: $member_service = new MemberService();         $member = $member_service->findMemberInfo([ 'wx_openid' => $wx_openid, 'site_id' => $this->site_id ]); ...
const member_service = this.memberService;
        const member = member_service.findMemberInfo([ wx_openid: wx_openid, site_id: this.site_id )];
        if (!member.isEmpty()) throw new AuthBusinessException('MEMBER_OPENID_EXIST');//openid已存在

        const member_info = member_service.findMemberInfo([ member_id: this.member_id, site_id: this.site_id )];
        if (member_info.isEmpty()) throw new AuthBusinessException('MEMBER_NOT_EXIST');//账号不存在
        member_service.editByFind(member_info, [ wx_openid: wx_openid )];
        return true;
    }
}
  }
}
